package com.midea.ai.air.ui.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.midea.ai.air.R;
import com.midea.ai.air.common.ActionBarBackFragment;
import com.midea.ai.air.common.BaseActivity;
import com.midea.ai.air.common.ConsVal;
import com.midea.ai.air.common.Constant;
import com.midea.ai.air.ui.home.fragment.AddDeviceConnectDeviceFragment;
import com.midea.ai.air.ui.home.fragment.AddDeviceConnectWifiFragment;
import com.midea.ai.air.ui.home.fragment.AddDeviceNetTipFragment;
import com.midea.ai.air.ui.home.fragment.AddDeviceSelectRoomFragment;
import com.midea.ai.air.ui.home.fragment.AddDeviceSetFragment;
import com.midea.ai.air.ui.home.fragment.EditDeviceManagerFragment;
import com.midea.ai.air.ui.home.fragment.EditRoomSceneFragment;
import com.midea.ai.air.ui.home.fragment.EditRoomSetFragment;
import com.midea.ai.air.ui.home.fragment.EditSceneSetFragment;
import com.midea.ai.air.ui.more.MoreFamilyAddMemberActivity;
import com.midea.ai.air.ui.more.fragment.MoreFamilyFragment;
import com.midea.ai.air.ui.more.fragment.MoreFamilySelectFragment;
import com.midea.ai.air.ui.more.fragment.MorePersonAddFragment;
import com.midea.ai.air.ui.more.fragment.MorePersonFragment;
import com.midea.ai.air.ui.more.fragment.MorePersonSexFragment;
import com.midea.ai.air.ui.more.fragment.SettingListFragment;
import com.midea.ai.air.utils.ComUtils;
import com.midea.ai.air.utils.JumpUtils;
import com.midea.ai.air.view.AlertCenterDialog;
import com.midea.ai.air.view.BottomDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ouyangdi on 2015/12/16.
 */
public class ActivityDetails extends BaseActivity {
    private String mStrTitle;
    private String mBtnText;
    private int mPageTag;
    private String mStrArg;
    private TextView mTvActionRight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);

        getIntentData();
        initActionBar();
        addContentFragment();
    }

    /**
     * 获取Intent携带的数据
     */
    private void getIntentData() {
        mStrTitle = getIntent().getStringExtra(ConsVal.KEY_TITLE);
        mBtnText = getIntent().getStringExtra(ConsVal.KEY_BACK_TEXT);
        mPageTag = getIntent().getIntExtra(ConsVal.KEY_PAGE_TAG, -1);
        mStrArg = getIntent().getStringExtra(ConsVal.KEY_ARG);
    }

    /**
     * 初始化顶部工具栏
     */
    private void initActionBar() {
        FrameLayout mBarLayout = (FrameLayout)findViewById(R.id.bar_parent);
        ViewGroup.LayoutParams LP = mBarLayout.getLayoutParams();
        LP.height = Constant.getTopMargin() + getResources().getDimensionPixelSize(R.dimen.height_44dp);
        mBarLayout.setLayoutParams(LP);

        ActionBarBackFragment backFragment = (ActionBarBackFragment)getSupportFragmentManager().findFragmentById(R.id.bar_fragment);
        backFragment.getBackButton().setText(mBtnText);
        backFragment.getTvTitle().setText(mStrTitle);

        switch (mPageTag) {
            case ConsVal.ACTIVITY_TAG_EDIT_ROOM_SET_SCENE_SET:
                backFragment.getTvBarRight().setText(getResources().getString(R.string.air_home_edit_room_bar_right));
                backFragment.getTvBarRight().setVisibility(View.VISIBLE);
                backFragment.getTvBarRight().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                });
                break;

            case ConsVal.ACTIVITY_TAG_EDIT_ROOM_DEVICE:
                mTvActionRight = backFragment.getTvBarRight();
                mTvActionRight.setText(getResources().getString(R.string.action_save));
                mTvActionRight.setVisibility(View.VISIBLE);
                mTvActionRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertCenterDialog dialog = new AlertCenterDialog(getContext()).builder().setTitle(getString(R.string.air_home_edit_room_dialog_title)).setMsg(getString(R.string.air_home_edit_room_dialog_content))
                                .setNegativeButton("", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                })
                                .setPositiveButton("",new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                            }
                                        }
                                );
                        dialog.show();
                    }
                });
                backFragment.getBackButton().setVisibility(View.GONE);
                backFragment.getTvBarLeft().setVisibility(View.VISIBLE);
                break;

            case ConsVal.ACTIVITY_TAG_MORE_FAMILY:
                backFragment.getTvBarRight().setText(mStrArg);
                backFragment.getTvBarRight().setVisibility(View.VISIBLE);
                backFragment.getTvBarRight().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ActivityDetails.this, MoreFamilyAddMemberActivity.class);
                        intent.putExtra(ConsVal.KEY_TITLE,getString(R.string.air_more_family_add_family_member));
                        intent.putExtra(ConsVal.KEY_ARG, getString(R.string.air_more_family_add));
                        startActivity(intent);
                    }
                });
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_NET_TIP:
                backFragment.getTvBarRight().setText(getString(R.string.register_next));
                backFragment.getTvBarRight().setVisibility(View.VISIBLE);
                backFragment.getTvBarRight().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JumpUtils.toPage(ActivityDetails.this, getString(R.string.air_add_device_connect_wifi), getString(R.string.action_bar_back),
                                ConsVal.ACTIVITY_TAG_ADD_DEVICE_CONNECT_WIFI, ActivityDetails.class);
                    }
                });
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_CONNECT_WIFI:
                backFragment.getTvBarRight().setText(getString(R.string.register_next));
                backFragment.getTvBarRight().setVisibility(View.VISIBLE);
                backFragment.getTvBarRight().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JumpUtils.toPage(ActivityDetails.this, getString(R.string.air_add_device_connect_device), getString(R.string.air_add_device_connect_cancel),
                                ConsVal.ACTIVITY_TAG_ADD_DEVICE_CONNECT_DEVICE, ActivityDetails.class);
                    }
                });
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_SET:
                backFragment.getBackButton().setVisibility(View.GONE);
                backFragment.getTvBarRight().setText(getString(R.string.accomplish));
                backFragment.getTvBarRight().setVisibility(View.VISIBLE);
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_SELECT_ROOM:
                backFragment.getIvBarRight().setImageResource(R.drawable.air_appliances_add);
                backFragment.getIvBarRight().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        List<BottomDialog.ListItem> mRooms = new ArrayList<>();
                        mRooms.add(new BottomDialog.ListItem(getString(R.string.air_home_edit_room_living)));
                        mRooms.add(new BottomDialog.ListItem(getString(R.string.air_home_edit_room_main)));
                        mRooms.add(new BottomDialog.ListItem(getString(R.string.air_home_edit_room_bedroom)));
                        mRooms.add(new BottomDialog.ListItem(getString(R.string.air_home_edit_room_study)));
                        mRooms.add(new BottomDialog.ListItem(getString(R.string.air_home_edit_room_other)));
                        new BottomDialog(ActivityDetails.this).builder().setTitle(getString(R.string.air_home_edit_room_new)).addListItems(mRooms).show();
                    }
                });
                backFragment.getIvBarRight().setVisibility(View.VISIBLE);
                break;

            default:
                break;
        }
    }

    private void addContentFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        switch (mPageTag) {
            case ConsVal.ACTIVITY_TAG_SET:
                SettingListFragment settingFragment = new SettingListFragment();
                ft.add(R.id.content_layout, settingFragment);
                ft.commit();
               break;

            case ConsVal.ACTIVITY_TAG_EDIT_ROOM_SET:
                EditRoomSetFragment roomSetFragment = new EditRoomSetFragment();
                roomSetFragment.setStrRoom(mStrArg);
                ft.add(R.id.content_layout, roomSetFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_EDIT_ROOM_SET_SCENE:
                EditRoomSceneFragment roomSceneFragment = new EditRoomSceneFragment();
                ft.add(R.id.content_layout, roomSceneFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_EDIT_ROOM_SET_SCENE_SET:
                EditSceneSetFragment sceneSetFragment = new EditSceneSetFragment();
                sceneSetFragment.setStrScene(mStrTitle);
                ft.add(R.id.content_layout, sceneSetFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_EDIT_ROOM_DEVICE:
                EditDeviceManagerFragment deviceFragment = new EditDeviceManagerFragment();
                ft.add(R.id.content_layout, deviceFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_MORE_PERSON:
                MorePersonFragment personFragment = new MorePersonFragment();
                ft.add(R.id.content_layout, personFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_MORE_PERSON_SEX:
                MorePersonSexFragment personSexFragment = new MorePersonSexFragment();
                ft.add(R.id.content_layout, personSexFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_MORE_PERSON_ADD:
                MorePersonAddFragment personAddFragment = new MorePersonAddFragment();
                ft.add(R.id.content_layout, personAddFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_MORE_FAMILY:
                MoreFamilyFragment moreFamilyFragment = new MoreFamilyFragment();
                ft.add(R.id.content_layout, moreFamilyFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_MORE_FAMILY_SELECT_FAMILY:
                MoreFamilySelectFragment moreFamilySelectFragment = new MoreFamilySelectFragment();
                ft.add(R.id.content_layout, moreFamilySelectFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_NET_TIP:
                AddDeviceNetTipFragment netTipFragment = new AddDeviceNetTipFragment();
                ft.add(R.id.content_layout, netTipFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_CONNECT_WIFI:
                AddDeviceConnectWifiFragment wifiFragment = new AddDeviceConnectWifiFragment();
                ft.add(R.id.content_layout, wifiFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_CONNECT_DEVICE:
                AddDeviceConnectDeviceFragment connectDeviceFragment = new AddDeviceConnectDeviceFragment();
                ft.add(R.id.content_layout, connectDeviceFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_SET:
                AddDeviceSetFragment setFragment = new AddDeviceSetFragment();
                ft.add(R.id.content_layout, setFragment);
                ft.commit();
                break;

            case ConsVal.ACTIVITY_TAG_ADD_DEVICE_SELECT_ROOM:
                AddDeviceSelectRoomFragment selectRoomFragment = new AddDeviceSelectRoomFragment();
                ft.add(R.id.content_layout, selectRoomFragment);
                ft.commit();
                break;

            default:
                break;
        }
    }

    //点击EditText以外的区域隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (ComUtils.isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(mPageTag == ConsVal.ACTIVITY_TAG_MORE_PERSON) {
            //获取头像保存的Uri
            MorePersonFragment fragment = (MorePersonFragment)getSupportFragmentManager().findFragmentById(R.id.content_layout);
            Uri fileUri = fragment.getFileUri();

            if(requestCode == ConsVal.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
                if(resultCode == RESULT_OK) {
                    //发送广播，刷新图库
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
                    startCropActivity(fileUri);
                } else if(resultCode == RESULT_CANCELED) {

                } else {

                }

            } else if(requestCode == ConsVal.CROP_ACTIVITY_REQUEST_CODE) {
                if(resultCode == RESULT_OK) {
                    //拿到剪切数据
                    Bitmap bmap = data.getParcelableExtra("data");
                    //设置头像
                    fragment.getHeadIcon().setImageBitmap(makeRoundCorner(bmap));
                }

            } else if(requestCode == ConsVal.GET_CONTENT_ACTIVITY_REQUEST_CODE) {
                if(resultCode == RESULT_OK) {
                    startCropActivity(data.getData());
                }
            }
            //关闭底部弹窗
            fragment.closeBotDialog();
        }
    }

    /**
     * 进入系统剪切Activity
     * @param inFileUri 待剪切的图片Uri
     */
    private void startCropActivity(Uri inFileUri) {
        //进入系统剪切Activity
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(inFileUri, "image/*");// mUri是已经选择的图片Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);// 输出图片大小
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, ConsVal.CROP_ACTIVITY_REQUEST_CODE);
    }

    /**
     * 制作圆形Bitmap
     * @param bitmap 输入
     * @return 输出
     */
    public static Bitmap makeRoundCorner(Bitmap bitmap)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int left = 0, top = 0, right = width, bottom = height;
        float roundPx = height/2;
        if (width > height) {
            left = (width - height) / 2;
            top = 0;
            right = left + height;
            bottom = height;
        } else if (height > width) {
            left = 0;
            top = (height - width) / 2;
            right = width;
            bottom = top + width;
            roundPx = width / 2;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(left, top, right, bottom);
        RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
}
